<?php
/**
 * 内容管理
 * @author cjli
 *
 */
class ArticleAction extends AdminAction
{
 	public function _initialize()
	{
		parent::_initialize();
	}
	 
	public function index()
	{
		$post = $_REQUEST;
		
		$where = array();

		//搜索分类
		if(isset($post['catid']) && $post['catid']){
			$cat_ids = CategoryModel::getCategoryChildIds($post['catid'], CategoryModel::TYPE_ARTICLE);
			$where['catid'] =  array('in', $cat_ids);
		}
		
	//搜索推荐
		if(isset($post['recommendid']) && $post['recommendid']){
			$where['ca.catid'] = $post['recommendid'];
		}
		//搜索关键词
		if(isset($post['keyword']) && $post['keyword']){
			if($post['searchtype']){
				$where['article.id'] = $post['keyword'];
			}else{
				$where['ari.name'] = array('like', '%'.$post['keyword'].'%');
			}
		}
		$article_db = M('article');
		if(isset($post['recommendid']) && $post['recommendid']){
			$article_db->join('category_article as ca on ca.aid=article.id');
		}
		//分页
		$article_db->where($where);
		$count = $article_db->count();//总记录数

		import("ORG.Util.Page");// 导入分页类
		$Page = new Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		//文章列表
		$artWhere = $where;
		$language_id = C('language_id') ? C('language_id') : 1;
		$artWhere['ari.language_id'] = $language_id;
		$artWhere['cat.language_id'] = $language_id;
		
		$article_db->field('article.id,ari.name,catid,start_time,end_time,visit,author,article.listorder,article.display,cat.name AS catname');
		$article_db->join('category_items AS cat ON cat.category_id=catid');
		$article_db->join('article_items AS ari ON ari.article_id=article.id');
		$article_db->order('article.listorder DESC, article.id DESC');
		$article_db->limit($Page->firstRow.','.$Page->listRows);
		if(isset($post['recommendid']) && $post['recommendid']){
			$article_db->join('category_article as ca on ca.aid=article.id');
		}
		$article_db->where($artWhere);
		$articleList = $article_db->select();
		$this->assign('articleList', $articleList);
		
		//文章推荐数组
		$recommendArray = array();
		$recommends = CategoryModel::getCategoryListBase(CategoryModel::TYPE_ARTICLE_RECOMMEND);
		foreach ($recommends as $cat){
			$recommendArray[$cat['id']] = $cat['name'];
		}
		$this->assign('recommendArray', $recommendArray);
		//下拉分类
		$catid = isset($catid) ? $catid : 0;
		$select_categorys = CategoryModel::categorySelectList($catid, CategoryModel::TYPE_ARTICLE); 
		$this->assign('select_categorys', $select_categorys);
		$this->assign('search', isset($post) ? $post : null);
		$this->display('article_list');
	}
	
	public function article_add()
	{
		if(isset($_POST['dosubmit']))
		{
			//上传图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['name']){
				$info = $this->upload('article');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					$_POST['img'] = UPLOAD_PATH . $info['upimage']['savename'];
				}else{
					$this->error($info);
				}
			}
			
			//自动提取缩略图
			$language_id = C('language_id');
			if(isset($_POST[$language_id]['auto_thumb']) && $_POST['img'] == '' && isset($_POST[$language_id]['description'])) {
				$content = $content ? $content : stripslashes($_POST[$language_id]['description']);
				$auto_thumb_no = intval($_POST[$language_id]['auto_thumb_no'])-1;
				if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
					$_POST[$language_id]['img'] = $matches[3][$auto_thumb_no];
				}
			}
			
			$aid = ArticleModel::updateArticleInfo($_POST);
			if($aid){
				ArticleModel::updateArticleItems($_POST['article'], $aid);
				//其他分类入库
				$this->insert_category_article($aid, $_POST['category_article']);
				$this->success('文章添加成功！', U('article/index'));
			}else{
				$this->error('文章添加失败！', U('article/index'));
			}
		}else{
			//文章推荐数组
			$recommendArray = array();
			$recommends = CategoryModel::getCategoryListBase(CategoryModel::TYPE_ARTICLE_RECOMMEND);
			foreach ($recommends as $cat){
				$recommendArray[$cat['id']] = $cat['name'];
			}
			$this->assign('recommendArray', $recommendArray);
			//下拉分类
			$select_categorys = CategoryModel::categorySelectList(0, CategoryModel::TYPE_ARTICLE); 
			$this->assign('select_categorys', $select_categorys);
			$this->display('article_form');
		}
	}
	
	//编辑文章
	public function article_edit()
	{
		$aid = intval($_GET['aid']);
		$articleInfo = ArticleModel::getArticleInfo($aid);
		if(!$articleInfo){
			$this->error('文章不存在！', U('article/index'));
		}
		if(isset($_POST['dosubmit']))
		{
			//上传图片
			if (isset($_FILES['upimage']) && $_FILES['upimage']['name']){
				$info = $this->upload('article');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					$_POST['img'] = UPLOAD_PATH . $info['upimage']['savename'];
				}else{
					$this->error($info);
				}
			}
			
			//自动提取缩略图
			$language_id = C('language_id');
			if(isset($_POST[$language_id]['auto_thumb']) && $_POST['img'] == '' && isset($_POST[$language_id]['description'])) {
				$content = $content ? $content : stripslashes($_POST[$language_id]['description']);
				$auto_thumb_no = intval($_POST[$language_id]['auto_thumb_no'])-1;
				if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
					$_POST[$language_id]['img'] = $matches[3][$auto_thumb_no];
				}
			}

			$aid = ArticleModel::updateArticleInfo($_POST, $aid);
			if($aid){
				ArticleModel::updateArticleItems($_POST['article'], $aid);
				//其他分类入库
				$this->insert_category_article($aid, $_POST['category_article']);
				$this->success('文章编辑成功！', U('article/index'));
			}else{
				$this->error('文章编辑失败！', U('article/edit', array('aid' => $aid)));
			}
		}else{
			
			//获取文章详细内容
			$articleInfo['items'] = ArticleModel::getArticleItems($aid);
			
			//文章推荐数组
			$recommendArray = array();
			$recommends = CategoryModel::getCategoryListBase(CategoryModel::TYPE_ARTICLE_RECOMMEND);
			foreach ($recommends as $cat){
				$recommendArray[$cat['id']] = $cat['name'];
			}
			$this->assign('recommendArray', $recommendArray);
			//推荐IDS
			$topIds = array();
			$category_article_db = D('category_article');
			$categoryArray = $category_article_db->field('catid')->where('aid='.$aid)->select();
			if($categoryArray){
				foreach ($categoryArray as $cat){
					$topIds[] = $cat['catid'];
				}
			}
			$this->assign('topIds', $topIds);
			//下拉分类
			$select_categorys = CategoryModel::categorySelectList($articleInfo['catid'], CategoryModel::TYPE_ARTICLE); 
			$this->assign('select_categorys', $select_categorys);
			$this->assign('article', $articleInfo);
			$this->display('article_form');
		}
	}
	
	//文章删除
	public function article_delete()
	{
		$aid = intval($_GET['aid']);
		$articleInfo = ArticleModel::getArticleInfo($aid);
		if(!$articleInfo){
			$this->error('文章不存在！', U('article/index'));
		}
		ArticleModel::deleteArticle($aid);
		$this->success('文章删除成功！', U('article/index'));
	}
	
	//单页列表
	public function page_list()
	{
		$where['pai.language_id'] = C('language_id') ? C('language_id') : 1;
		$page_db = D('page');
		$page_db->field('id,pai.name,start_time,listorder');
		$page_db->join('page_items AS pai ON pai.page_id = page.id');
		$pageList = $page_db->where($where)->order('listorder DESC, id ASC')->select();
		$this->assign('pageList', $pageList);
		$this->display('page_list');
	}
	
	//添加单页
	public function page_add()
	{
		if(isset($_POST['dosubmit'])){
			$pid = ArticleModel::updatePageInfo($_POST);
			if($pid){
				ArticleModel::updatePageItems($_POST['article'], $pid);
				$this->success('单页添加成功！',  U('article/page_list'));
			}else{
				$this->error('单页添加失败！',  U('article/page_list'));
			}
		}else{
			$this->display('page_form');
		}
	}
	
	//单页编辑
	public function page_edit()
	{
		$pid = intval($_GET['pid']);
		$pageInfo = ArticleModel::getPageInfo($pid);
		if(!$pageInfo){
			$this->error('文章不存在!', U('article/page_list'));
		}
		if(isset($_POST['dosubmit']))
		{
			ArticleModel::updatePageInfo($_POST, $pid);
			ArticleModel::updatePageItems($_POST['article'], $pid);
			$this->success('单页编辑成功！',  U('article/page_list'));
		}else{
			$pageInfo['items'] = ArticleModel::getPageItems($pid);
			$this->assign('page', $pageInfo);
			$this->display('page_form');
		}
	}
	
	//单页删除
	public function page_delete()
	{
		$pid = intval($_GET['pid']);
		$pageInfo = ArticleModel::getPageInfo($pid);
		if(!$pageInfo){
			$this->error('文章不存在!', U('article/page_list'));
		}
		ArticleModel::deletePageInfo($pid);
		$this->success('文章删除成功！', U('article/page_list'));
	}
	
	/**
	 * 文章推荐关联入库
	 * @param int $aid 文章ID
	 * @param array $cat_array 推荐ID数组
	 */
	private function insert_category_article($aid, $cat_array)
	{
		$category_article_db = D('category_article');
		$category_article_db->where('aid='.$aid)->delete();
		if(is_array($cat_array) && count($cat_array)>0){
			foreach ($cat_array as $catid){
				$data = array(
					'catid' => $catid,
					'aid' => $aid,
				);
				$category_article_db->add($data);
			}
		}
	}
	
	//修改文章排序
	public function change_article_listorder_ajax()
	{
		$aid = intval($_GET['aid']);
		$listorder = intval($_GET['listorder']);
		$article_db = D('article');
		$article_db->where('id='.$aid)->save(array('listorder' => $listorder));
	}
	
	//修改单页排序
	public function change_page_listorder_ajax()
	{
		$pid = intval($_GET['pid']);
		$listorder = intval($_GET['listorder']);
		$page_db = D('page');
		$page_db->where('id='.$pid)->save(array('listorder' => $listorder));
	}
	
	//修改文章状态
	public function change_status_ajax()
	{
		$aid = intval($_GET['aid']);
		$display = intval($_GET['display']);
		$article_db = D('article');
		$article_db->where('id='.$aid)->save(array('display' => $display));
	}

   //媒体新闻
    public function media_reports()
    {
		
		$where = array();
		//搜索关键词
		$keyword = trim($_REQUEST['keyword']);
		if($keyword){
		    $map['path_alias'] = array('like', '%'.$keyword.'%');
		    $map['path_alias2'] = array('like', '%'.$keyword.'%');
		    $map['_logic'] = 'OR'; 
		    $where['_complex'] = $map;
			$this->assign('keyword', $keyword);
		}
		if($_REQUEST['media_type']){
		    $where['media_type']  = intval($_REQUEST['media_type']);
		    $this->assign('media_type', intval($_REQUEST['media_type']));
		}
       	$pageRows = 15;
		$media_db = D('media');
		$count = $media_db->where($where)->count();
		import("ORG.Util.Page");
		$Page = new Page($count,$pageRows);
		$pageShow = $Page->show();
		$media_db->limit($Page->firstRow.','.$Page->listRows);
		$mediaList = $media_db->where($where)->order('listorder asc')->select();//echo  D('media')->getLastSql();
		$this->assign('pageShow', $pageShow);
		$this->assign('mediaList', $mediaList);
		$this->display('mediareports');
    }
    
 //添加媒体新闻
    public function mediareports_add()
    {
        if(isset($_POST['dosubmit'])){
			//dump($_POST);exit;
            if (isset($_FILES['upimage_adv']) && $_FILES['upimage_adv']['name']){
                $info = $this->upload('article');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					if($info['upimage_adv']){
						$_POST['media_img'] = UPLOAD_PATH . $info['upimage_adv']['savename'];
					}
                }else{
                    $this->error($info);
                }
            }
            if($_POST['path_alias']=="http://"){
                $_POST['path_alias']=null;
            }
            if($_POST['path_alias2']=="http://"){
                $_POST['path_alias2']=null;
            }
            $media_db = D('media');
            $mediaId = $media_db->add($_POST);
            if($mediaId){
                $this->success('媒体新闻操作成功！', U('article/media_reports'));
            }else{
                $this->error('媒体新闻操作失败！', U('article/mediareports_add'));
            }
        }
			$miedia_type = C('miedia_type');
			$this->assign('miedia_type',$miedia_type);
            $this->display('mediareports_add');
       
    }
    //编辑媒体新闻
    public function mediareports_edit()
    {
        $aid = intval($_GET['aid']);
        $media_db = D('media');
        $mediaInfo = $media_db->find($aid);
        if(!$mediaInfo){
            $this->error('数据不存在！', U('article/media_reports'), 'edit');
        }

        if(isset($_POST['dosubmit'])){
            if (isset($_FILES['upimage_adv']) && $_FILES['upimage_adv']['name']){
                $info = $this->upload('article');
				//dump($info);exit;
				if(is_array($info)) {// 上传成功 获取上传文件信息
					if($info['upimage_adv']){
						$_POST['media_img'] = UPLOAD_PATH . $info['upimage_adv']['savename'];
					}
                }else{
                    $this->error($info);
                }
            }
            $media_db = D('media');
            if($_POST['path_alias']=="http://"){
                $_POST['path_alias']=null;
            }
            if($_POST['path_alias2']=="http://"){
                $_POST['path_alias2']=null;
            }
            $mediaId = $media_db->where('id='.$aid)->save($_POST);
            if($mediaId){
                $this->success('媒体新闻修改成功！', U('article/media_reports'));
            }else{
                $this->error('媒体新闻修改失败！', U('article/media_reports'));
            }
        }
			$miedia_type = C('miedia_type');
			$this->assign('miedia_type',$miedia_type);
        	$this->assign('mediaInfo',$mediaInfo);
            $this->display('mediareports_edit');
    }

    //删除媒体新闻
    public function mediareports_delete()
    {
        $aid = intval($_GET['aid']);
        $media_db = D('media');
        $media_db->delete($aid);
        $this->success('删除成功！', U('article/media_reports'));
    }
	//媒体新闻排序
	public function MediaListOrder()
	{
		if(isset($_POST['dosubmit'])) {
			$catdb = D('media');
			foreach($_POST['listorders'] as $id => $listorder) {
				$catdb->where(array('id'=>$id))->save(array('listorder'=>$listorder));
			}
			S('admin_category_list_base_'.$this->_vid, NULL);
			$this->success('排序操作成功！');
		} else {
			$this->error('排序操作失败！');
		}
	}

}